package pl.auction_search.search;

import java.lang.reflect.Method;

import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.TextPropertyDescriptor;

public class ResultPropertySource implements IPropertySource {
	protected Result result;

	public ResultPropertySource(Result result) {
		this.result = result;
	}

	@Override public Object getEditableValue() {
		return this;
	}

	@Override public IPropertyDescriptor[] getPropertyDescriptors() {
		return new IPropertyDescriptor[] {
				new TextPropertyDescriptor("name", "Name"), 
				new TextPropertyDescriptor("url", "URL"), 
				new TextPropertyDescriptor("description", "Description"),
				new TextPropertyDescriptor("category", "Category"), 
				new TextPropertyDescriptor("engine", "Search Engine"),
		};
	}

	@Override public Object getPropertyValue(Object id) {
		try {
			return getGetter(result, id).invoke(result, new Object[0]);

		} catch (Exception e) {
			SearchHelper.handleException(e);
			return "mr_" + id;
		}
	}

	private Method getGetter(Result result2, Object id_) throws SecurityException, NoSuchMethodException {
		String id = id_.toString();
		String method = "get"+id.substring(0,1).toUpperCase()+id.substring(1);
		return result.getClass().getMethod(method, new Class<?>[0]);
	}

	@Override public boolean isPropertySet(Object arg0) {
		return false;
	}

	@Override public void resetPropertyValue(Object arg0) {
	}

	@Override public void setPropertyValue(Object id, Object value) {
		try {
			result.getClass().getField((String) id).set(result, value);
			
		} catch (Exception e) {
			SearchHelper.handleException(e);
		}
	}
}
